<template>
  <section
    ref="dialogWrap"
    v-if="isShow"
    id="videoPlayerWrap"
    class="dialog-wrap"
  >
    <div @click.stop="back" class="close"><i></i><i></i></div>
    <likeUpsComponent
      :key="key"
      v-if="fullDetail"
      class="like-ups-btns"
      :data="fullDetail"
    ></likeUpsComponent>

    <div class="video-wrap bg-black single-video" v-if="videoUrl">
      <div
        class="video"
      >
        <!-- <div
          v-if="!playing"
          class="poster"
          :style="{ 'background-image': 'url(' + getPoster(detail) + ')' }"
        >
          <img :src="getPoster(detail)" alt="" />
        </div> -->
        <div class="self">
          <div class="video-player">
            <div
              @click="doPlay"
              class="video-player"
              id="videoPlayerCom"
              :style="{ 'background': playing ? '#000' : 'url(' + getPoster(fullDetail) + ')' }"
            ></div>
          </div>
        </div>
        <div class="video-title">
          <p @click="userInfo" class="text">
            <span class="inner-text">@{{ nickName }}</span>
          </p>
          {{ getVideoTitle(detail) }}
        </div>
      </div>
    </div>

    <div class="video-wrap bg-black" v-if="currentIndex == '1' && !videoUrl">
      <cube-slide
        :showDots="false"
        :autoPlay="false"
        :direction="'vertical'"
        :loop="false"
        :style="{ width: '100vw' }"
        ref="slide"
        :data="list"
        @change="changePage"
      >
        <cube-slide-item
          :style="{ width: '100vw', height: scrollHeight + 'px' }"
          v-for="(item, idx) in list"
          :key="idx"
          @click.native.stop="clickHandler(item, idx)"
        >
          <div :style="{ height: scrollHeight + 'px' }" class="video">
            <video
              :key="idx"
              :poster="getPoster(item)"
              loop="loop"
              v-if="idx == 0"
              :src="getVideoSrc(item)"
              preload="auto"
              autoplay="autoplay"
            ></video>
            <img
              v-if="isShowImg"
              src="../../../static/images/dangjian/home/stop.png"
            />
            <!--            <video  :poster="getPoster(item)"  loop="loop" v-if="idx > 0" :src="getVideoSrc(item)" preload="auto"></video>-->
            <video
              :poster="getPoster(item)"
              loop="loop"
              v-if="idx > 0"
              :src="getVideoSrc(item)"
              preload="auto"
            ></video>
            <div class="video-title">
              <p @click="userInfo" class="text">
                <span class="inner-text">@{{ nickName }}</span>
              </p>
              {{ getVideoTitle(item) }}
            </div>
          </div>
        </cube-slide-item>
      </cube-slide>
    </div>
    <readScore
      ref="scoreInstanceVideo"
      v-if="fullDetail.detail && fullDetail.detail.newsContent"
      :_contentId="fullDetail.detail.newsContent.id"
      :type="2"
    ></readScore>
  </section>
</template>

<script>
import likeUpsComponent from "./likeUpsComponent";
import $ from "../../../static/js/jquery-1.12.4.min";
import _ from "lodash";
import Axios from "axios";
let playEndFn = null;
let timeupdateFn = null;
let player = null;
export default {
  components: { likeUpsComponent },
  name: "videoPlayerComponent",
  props: ["videoUrl", "list", "id"],
  data() {
    return {
      isShowImg: false,
      currentIndex: 1,
      isShow: !true,
      playing: !true,
      fullDetail: {},
      key: "",
      nickName: "",
      detail: {},
      newsDetail: {
        newsContent: null,
        files: null,
        upOrDown: null,
        collected: null,
      },
    };
  },
  watch: {
    videoUrl(val, oldVal) {
      this.fullDetail = {};
      this.key = Date.now();
      this.detail = this.$store.state.newsDetail;
      console.log("this.detailthis.detail",this.detail);
      this.loadData(this.detail.id);
      console.log("videoUrl");
    },
    $route(to, from) {
      this.back();
    },
  },
  created() {
    this.isShowImg = false;
    console.log("videoPlayerComponent created");
    /* if (this.videoUrl) {
      this.detail = this.$store.state.newsDetail;
      this.loadData(this.detail.id);
    } */
  },
  mounted() {
    window.goBackMethod = () => {
      this.goBackMethod();
    };
  },
  beforeDestroy() {
    this.tools.dialogDestroy();
  },
  methods: {
    /*阿里播放器*/
    aliplay(data) {
      var player = new Aliplayer(
        {
          id: "videoPlayerCom",
          source: this.getVideoSrc(data),
          preload: true,
          playsinline: true,
          useH5Prism: true,
          skinLayout: [
            {
              name: "H5Loading",
              align: "cc",
            },
            {
              name: "controlBar",
              align: "blabs",
              x: 0,
              y: 0,
              children: [
                { name: "progress", align: "blabs", x: 0, y: 44 },
                { name: "timeDisplay", align: "tl", x: 10, y: 7 },
              ],
            },
          ],
          autoplay: true,
          rePlay: true,
          controlBarVisibility: "click",
          showBarTime: "10000",
          height: "100%",
        },
        function (player) {
          player.play();
        }
      );
      $('.prism-error-operation').hide();
      $('.prism-error-content p').hide();
      $('.prism-error-content').append('<p style="margin-top: 50px;">播放出错啦！</p>');
      this.videoPlayerEvent(player);
    },
    /*阿里播放的事件、方法*/
    videoPlayerEvent(player) {
      let playBtn = `<div class="prism-big-play-btn center" style="display: none;"><div class="outter"></div></div>`;
      let me = this;
      $("#videoPlayerCom").append(playBtn)
        .on("click", function () {
          var aaa = player.getStatus();
          console.log('aaa',aaa)
          if (player.getStatus() !== "playing") {
            player.mypause = true; // 手动暂停时需要接着播放
            player.play();
            $(this).find(".prism-big-play-btn").fadeOut(500);
          } else {
            player.pause();
            $(this).find(".prism-big-play-btn").show();
          }
        });
      player.on("ended", () => {
        console.log("video ended");
        this.onended();
      });
      player.on("play", () => {
        if (!player.mypause) {
          $("#videoPlayerCom")
            .find(".prism-big-play-btn")
            .hide();
          player.seek(0);
        }
        player.mypause = false;
        me.onplay();
      });
      let consoleTime = Date.now();
      player.on("timeupdate", () => {
        if (Date.now() - consoleTime > 3 * 1000) {
          console.log("timeupdate", player.getCurrentTime());
          consoleTime = Date.now();
        }
      });
    },



    listenVideo() {
      this.isShowImg = false;
      let time = Date.now();
      let me = this;
      document.addEventListener("touchstart", () => {
        let myVideo = document.querySelector("video");
        myVideo && myVideo.play();
      });
      console.log("listenVideo");
      function reTryListen() {
        let nowTime = Date.now();
        if (nowTime - time > 3000) {
          console.log("视频监听失败");
          return false;
        }
        setTimeout(() => {
          let myVideo = document.querySelector("video");
          if (!myVideo) {
            console.log("视频监听");
            return reTryListen();
          }
          myVideo.addEventListener("ended", () => {
            console.log("player ended");
            me.onended();
          });
          myVideo.addEventListener("play", () => {
            console.log("player play");
            console.log("video time", myVideo.duration);
            me.onplay();
          });
          if (!timeupdateFn) {
            function timeupdate(e) {
              let myVideo = document.querySelector("video");
              console.log("timeupdate");
              if (myVideo && myVideo.duration <= myVideo.currentTime + 0.5) {
                console.log("myVideo ended");
                console.log(e);
                me.onended();
              }
            }
            timeupdateFn = timeupdate;
          }
          if (!playEndFn) {
            playEndFn = function () {
              me.onended();
            };
          }
          myVideo.removeEventListener("timeupdate", timeupdateFn);
          myVideo.addEventListener("timeupdate", timeupdateFn);
          myVideo.play();
        }, 100);
      }
      reTryListen();
    },
    onended() {
      // 两次播放完成时间不可能低于2分钟
      clearTimeout(this.$refs.scoreInstanceVideo.watchTimer);
      this.$refs.scoreInstanceVideo.watchTimer = setTimeout(() => {
        this.$refs.scoreInstanceVideo.getScore("watch");
      }, 1000);
    },
    doPlay() { //data
      /* let str = data ? data : "";
      console.log("video doplayaaaaa");
      this.isShowImg = false;
      if (str.toString().indexOf("child") != -1) {
        return;
      }
      this.$nextTick(() => {
        document.querySelector("video").play();
        this.$refs.scoreInstanceVideo &&
          this.$refs.scoreInstanceVideo.startRead();
      }); */
    },
    onplay() {
      setTimeout(() => {
        if (this.isShowImg == false) {
          this.doPlay();
          this.playing = true;
        }
      }, 5);
    },
    /*拉取用户信息*/
    fetchUserInfo(userId) {
      console.log("userId", userId);
      this.fetchService.getUserInfo(userId).then((res) => {
        this.nickName = res.qq || res.fullname;
      });
    },
    userInfo() {
      if (this.detail.createUser) {
        this.$router.push({
          name: "microVideo",
          query: { userId: this.detail.createUser },
        });
      } else if (this.detail.detail.newsContent.createUser) {
        // this.$router.push({name: 'microVideo', query: {userId: this.detail.detail.newsContent.createUser}})
        this.$router.push({
          name: "microVideo",
          query: { userId: this.detail.detail.newsContent.createUser },
        });
        // window.location.reload()
      }
    },
    getVideoTitle(item) {
      console.log("getVideoTitle", item);
      return item && item.detail && item.detail.newsContent.title;
    },
    changePage(currIndex) {
      console.log("当前轮播图序号为:" + currIndex);
      this.playVideo(currIndex);
      if (this.list.length - currIndex < 3) {
        this.fetchList();
      }
    },
    //获取内容详情(新)
    contentDetailNew(id) {
      let me = this;
      return me.fetchService.contentDetailNew(id).then((res) => {
        if (res.code === 0) {
          return res.data.newsContent;
        }
      });
    },
    //获取新闻附件
    newsFiles(id) {
      let me = this;
      return me.fetchService.newsFiles(id).then((res) => {
        if (res.code === 0) {
          return res.data;
        }
      });
    },
    //查询当前用户是否点赞指定的新闻
    contentGetSfdz(id) {
      let me = this;
      return me.fetchService.contentGetSfdz(id).then((res) => {
        if (res.code === 0) {
          return res.data;
        }
      });
    },
    //查询当前用户是否收藏指定的新闻
    contentGetSfsc(id) {
      let me = this;
      return me.fetchService.contentGetSfsc(id).then((res) => {
        if (res.code === 0) {
          return res.data;
        }
      });
    },
    loadData(id) {
      var me = this;
      return Axios.all([
        me.contentDetailNew(id),
        me.newsFiles(id),
        me.contentGetSfdz(id),
        me.contentGetSfsc(id),
      ])
        .then(
          Axios.spread((res1, res2, res3, res4) => {
            me.newsDetail.newsContent = res1;
            me.newsDetail.files = res2;
            me.newsDetail.upOrDown = res3;
            me.newsDetail.collected = res4;

            me.$store.state.newsDetail.detail = me.newsDetail;
            me.fullDetail = me.$store.state.newsDetail;
            me.detail.newsContent = me.fullDetail.newsContent;
            console.log('111111',me.fullDetail)
            me.$nextTick(() => {
              me.aliplay(me.fullDetail);
            });
            me.fetchUserInfo(me.detail.detail.newsContent.createUser);
          })
        )
        .catch((err) => {
          console.log(err.response);
        });

      /* this.fetchService.contentPageDetail(id).then((res) => {
        if (res.code === 0) {
          this.$store.state.newsDetail.detail = res.data;
          this.fullDetail = this.$store.state.newsDetail;
          this.detail.newsContent = this.fullDetail.newsContent;
          console.log("videoplay", res.data, this.$store.state.newsDetail);
        }
      }); */
    },
    playVideo(e) {
      // if (typeof e === 'object') {
      //   if (!e.target.playing) {
      //     e.target.playing = true
      //     e.target.play()
      //     return this.isShowImg = false
      //   }
      //   e.target.playing = false
      //   e.target.pause()
      //   this.isShowImg = true
      //
      // }
      if (this.isShowImg) {
        e.target.playing = true;
        e.target.play();
        return (this.isShowImg = false);
      }
      e.target.playing = false;
      e.target.pause();
      this.isShowImg = true;
    },
    comment(item) {
      console.log("comment", item);
      this.$store.state.newsDetail = item;
      this.$createCommentComponent({
        $props: {
          _contentId: item.id,
        },
      }).show();
    },
    getVideoSrc(item) {
      if(this.tools.indexOfHttp(item.detail.files[0].fileOssUrl)){
        return item.detail.files[0].fileOssUrl
      }
      return this.tools.getImgUrl(item.detail.files[0].fileId);
    },
    getPoster(item) {
      if(this.tools.indexOfHttp(item.listPicUrl)){
        return item.detail.files[0].fileOssUrl
      }
      return this.tools.getImgUrl(item.listPic);
    },
    show() {
      this.tools.stopAudio();
      this.tools.dialog(1, this);
      this.isShow = true;
      this.$nextTick(() => {
        // this.listenVideo();//WYB注释
      });
      if (this.videoUrl) {
        this.detail = this.$store.state.newsDetail;
        console.log("this.detail.detail", this.detail.detail);
        // this.nickName = this.detail.detail.newsContent.nickname;
        this.loadData(this.detail.id);
      }
    },
    back() {
      this.tools.playAudio();
      this.tools.dialog(-1);
      this.isShow = false;
    },
    goBackMethod() {
      if (this.isShow) {
        this.isShow = false;
        return "notShow";
      } else {
        return "";
      }
    },
  },
};
</script>

<style scoped lang="scss">
@import "@/common/stylus/moon.scss";
.dialog-wrap {
  position: fixed;
  z-index: 20;
  width: 100vw;
  height: 100vh;
  let: 0;
  top: 0;
  background: #000;
  .single-video,
  .video {
    @include fullImg();
    overflow: hidden;
    position: relative;
    video {
      width: 100%;
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }
  .video-wrap,
  .video {
    @include fullImg();
    video {
      z-index: auto !important; //为了暂停键
    }
  }
}
.like-ups-btns {
  position: absolute;
  top: 50%;
  right: 20px;
  z-index: 89;
  transform: translateY(-50%);
}
.close {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 89;
  width: pxToRem(30px);
  height: pxToRem(30px);
  transform: rotate(45deg);
  i {
    background: #999;
    position: absolute;
  }
  i:first-child {
    top: 50%;
    left: 0;
    margin-top: -1px;
    width: pxToRem(30px);
    height: 2px;
  }
  i:last-child {
    top: 0;
    left: 50%;
    margin-left: -1px;
    height: pxToRem(30px);
    width: 2px;
  }
}
.video {
  background-size: 100% auto;
  background-repeat: no-repeat;
  background-position: center;
  video::-webkit-media-controls {
    display: none !important;
  }
  .poster {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 3;
    overflow: hidden;
    background-color: $theme-color;
    background-size: 100% auto;
    background-repeat: no-repeat;
    background-position: center;
    img {
      z-index: 4;
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 100%;
      height: auto;
    }
  }
  .self {
    position: relative;
    z-index: 1;
    width: 100%;
    height: 100%;
    min-height: 100vh;
    > img {
      position: absolute;
      top: 46%;
      left: 41%;
      z-index: 1;
    }
  }
}


.video-player {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 1 !important;
  width: 100%;
  height: 100%;
  video {
    z-index: 1 !important;
  }
}
.video-wrap .video .video-title {
  width: 70%;
}
</style>
